import React, { useEffect } from "react"
import { Space, Table, Button } from "antd"
import { ColumnType } from "antd/es/table"
import { PlusOutlined } from "@ant-design/icons"
import dayjs from "dayjs"

import { TableToolbar } from "app/components"
import { useDept } from "./useDept"
import EditModal from "./EditModal"

const Dept: React.FC = () => {
  const {
    getList,
    handleDelete,
    submitForm,
    loading,
    dataSource,
    queryParams,
    setQueryParams,
    initForm,
    form,
    setForm,
    modalConfig,
    setModalConfig
  } = useDept()

  // 搜索栏
  const componentProps = [
    {
      col: 5,
      key: "deptName",
      type: "input",
      label: "部门名称",
      labelwidth: 90,
      placeholder: "请输入部门名称"
    },
    {
      col: 4,
      key: "status",
      type: "select",
      label: "状态",
      labelwidth: 40,
      placeholder: "请选择部门状态"
    }
  ]

  const openModal = (row) => {
    setForm(row.deptId ? { ...row } : { ...initForm })
    setModalConfig({ ...modalConfig, visible: true })
  }

  // table配置
  const columns: ColumnType<any>[] = [
    {
      title: "部门名称",
      align: "center",
      dataIndex: "deptName"
    },
    {
      title: "排序",
      align: "center",
      dataIndex: "orderNum"
    },
    {
      title: "状态",
      align: "center",
      dataIndex: "status"
    },
    {
      title: "创建时间",
      align: "center",
      render: (text, row) => (
        <span>{dayjs(row.createTime).format("YYYY-MM-DD HH:mm:ss")}</span>
      )
    },
    {
      title: "操作",
      align: "center",
      width: 80,
      render: (text, row) => (
        <Space size="small">
          <Button type="link" block onClick={() => openModal(row)}>
            修改
          </Button>
          <Button type="link" block onClick={openModal}>
            新增
          </Button>
          <Button type="link" block onClick={() => handleDelete(row.deptId)}>
            删除
          </Button>
        </Space>
      )
    }
  ]

  // 页面初始化
  useEffect(() => {
    getList()
  }, [])

  const buttonProps = [
    {
      label: "新增",
      icon: <PlusOutlined />,
      onClick: openModal
    }
  ]

  return (
    <>
      <TableToolbar
        getList={getList}
        queryParams={queryParams}
        setQueryParams={setQueryParams}
        buttonProps={buttonProps}
        componentProps={componentProps}
      />
      <Table
        loading={loading}
        columns={columns}
        dataSource={dataSource}
        pagination={{ hideOnSinglePage: true }}
        expandRowByClick
        rowKey="deptId"
      />

      <EditModal
        form={form}
        setForm={setForm}
        modalConfig={modalConfig}
        setModalConfig={setModalConfig}
        treeData={dataSource}
        submitForm={submitForm}
      />
    </>
  )
}

export default Dept
